package okhttp;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.bcel.internal.generic.NEW;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author ZH
 */
public class OkHttpTest {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static void main(String[] args) throws IOException {
        getRequest();
        //postRequest();
        //postJsonRequest();
    }

    public static void getRequest() throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                //.url("http://localhost:9001/business/function/page") //不带参数
                .url(HttpUrl.parse("http://httpbin.org/get")
                        .newBuilder()
                        .addQueryParameter("current","1")
                        .addQueryParameter("size","2")
                        .build())
                .get()
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.code());
        System.out.println(response.body().string());
    }
    public static void postRequest() throws IOException{
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder form = new FormBody.Builder();
        form.add("password", "21232f297a57a5a743894a0e4a801fc3");
        form.add("tenantId", "000000");
        form.add("username", "admin");
        Request request = new Request.Builder()
                .url("http://localhost:9001/blade-auth/oauth/token")
                .addHeader("Authorization","Basic c3dvcmQ6c3dvcmRfc2VjcmV0")
                .post(form.build())
                 .build();
        Response response = client.newCall(request).execute();
        String body = response.body().string();
        JSONObject json = (JSONObject)JSONObject.parse(body);
        String token = json.getString("access_token");
        System.out.println(token);
    }

    public static void postJsonRequest() throws IOException {
        OkHttpClient client = new OkHttpClient();

        Map<String, Object> map = new HashMap<>();
        map.put("name", "Tom");
        map.put("age", 23);

        String data = JSONObject.toJSONString(map);
        RequestBody requestBody = RequestBody.create(data, JSON);

        Request request = new Request.Builder()
                .url("http://httpbin.org/post")
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
}
